﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Fcdbas.Platform.Properties;
using Fcdbas.WinUI.Forms;

namespace Fcdbas.WinUI.Controls
{
    [Description("表示 Fcdbase 富文本控件，用来显示文本。")]
    [ToolboxBitmap(typeof(System.Windows.Forms.RichTextBox))]
    [ToolboxItemFilter("System.Windows.Forms")]
    public class cRichEdit : DevExpress.XtraRichEdit.RichEditControl, IReference, IOwningDataSourceBinding, IReadOnly, IValidate, IControl
    {

        public cRichEdit()
        {
           // this.OpenDocumentBytesChanged += new EventHandler(cRichEdit_OpenDocumentBytesChanged);
            this.ContentChanged += new EventHandler(cRichEdit_ContentChanged);
           
        }
        public bool IsOpen = false;
        public override void LoadDocument()
        {
            base.LoadDocument();
            IsOpen = true;
        }
        public override void LoadDocument(IWin32Window parent)
        {
            base.LoadDocument(parent);
            IsOpen = true;
        }
        public override void LoadDocument(string fileName)
        {
            base.LoadDocument(fileName);
            IsOpen = true;
        }
        public override void LoadDocument(string fileName, DevExpress.XtraRichEdit.DocumentFormat documentFormat)
        {
            base.LoadDocument(fileName, documentFormat);
            IsOpen = true;
        }
        public override void LoadDocument(System.IO.Stream stream, DevExpress.XtraRichEdit.DocumentFormat documentFormat)
        {
            base.LoadDocument(stream, documentFormat);
            IsOpen = true;
        }
        
        protected override void OnDocumentLoaded(object sender, EventArgs e)
        {
            base.OnDocumentLoaded(sender, e);
            if(IsOpen)
                ModifyObject();
            IsOpen = false;
        }
        protected override void OnModifiedChanged(object sender, EventArgs e)
        {
            base.OnModifiedChanged(sender, e);
            cRichEdit_ContentChanged(sender, e);
        }
        void cRichEdit_ContentChanged(object sender, EventArgs e)
        {
            if (!this.Modified)
                return;
            ModifyObject();
        }
        private void ModifyObject()
        {
            if (OwningDataSourceBinding != null)
            {
                if (OwningDataSourceBinding.Updates == Platform.Enums.UpdatesSql.ReadOnly)
                    return;
                //if (!OwningDataSourceBinding.AllowEdit)
                //    return;
                if (!OwningDataSourceBinding.Session.IsNew && !OwningDataSourceBinding.Session.IsEdit && !OwningDataSourceBinding.Binding && !OwningDataSourceBinding.Session.RecordRefresh)
                {
                    Form frm = WinUI.Common.WinUtil.GetParentForm(this);
                    if (frm != null)
                        Fcdbas.Core.Windows.SalWindow.FireWindowActions(frm, Fcdbas.Platform.Const.AM_DataSourceFieldModified, 1, OwningDataSourceBinding.Identify);
                    IsEditing = true;
                }
                Fcdbas.Core.IEntity en = OwningDataSourceBinding.Current as Fcdbas.Core.IEntity;
                if (en != null && GetBindingItem() != null)
                {
                    if (OpenDocumentBytes != null)
                    {

                        en[GetBindingItem().ColumnName] = OpenDocumentBytes;

                    }
                    else
                        en[GetBindingItem().ColumnName] = null;
                }
            }

            FireRef = true;
        }
       
        
        
        private cLabel bindLabel;
        public cLabel BindLabel
        {
            get
            {
                return this.bindLabel;
            }
            set
            {
                this.bindLabel = value;
            }
        }
        public string Label
        {
            get
            {
                if (bindLabel != null)
                    return bindLabel.Text;
                else
                    return "";
            }

        }


        [Browsable(false)]
        public string FileName
        {
            get
            {
                if (string.IsNullOrEmpty(_filePath))
                    return "";
                return Fcdbas.Core.Util.FileHelper.GetFileNameNoPath(_filePath);
            }
            set
            {

            }
        }
        /// <summary>
        /// 绑定的字段信息
        /// </summary>
        public DataItem DataColumn
        {
            get;
            set;
        }
        #region IReference 成员
        public bool IsDelete
        {
            set
            {
                if (value)
                {
                    Font font = new Font(this.Font, FontStyle.Strikeout);
                    this.Font = font;
                    oldForeColor = this.ForeColor;
                    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.DeleteColor;
                }
                else
                {
                    Font font = new Font(this.Font, FontStyle.Regular);
                    this.Font = font;
                    this.ForeColor = oldForeColor;
                }
            }
        }
        public string Value
        {
            get
            {
                return this.Text;
            }
            set
            {
                this.Text = value;
            }
        }
        private bool _isEditing;
       
        public bool IsEditing
        {
            get
            {
                return _isEditing;
            }
            set
            {
                _isEditing = value;
                //if (value)
                //{
                //    this.oldForeColor = this.ForeColor;
                //    this.ForeColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.EditColor;
                //}
                //else
                //{
                //    this.ForeColor = oldForeColor;
                //}
            }
        }
        public bool IsReference
        {
            get
            {
                return !string.IsNullOrEmpty(Reference);
            }
        }

        public string Reference
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.Reference;

                return null;
            }
        }

        private string columnName;
        public string Column
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.ColumnName;
                else
                    return columnName;
            }
            set
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    bindingItem.ColumnName = value;
                columnName = value;
            }
        }

        public Type DataType
        {
            get
            {
                DataItem bindingItem = GetBindingItem();
                if (bindingItem != null)
                    return bindingItem.DataType;

                return null;
            }
        }

        public object ReferenceValue
        {
            get
            {
                return this.Text;
            }
        }

        public void SetValue(object value)
        {
            if (value == null ||
                value is DBNull)
                return;

            this.Text = value.ToString();
        }

        #endregion

        private DataItem GetBindingItem()
        {
            return DataColumn;

        }
        
        private DataSourceBinding GetOwningDataSourceBinding()
        {
            DataSourceBinding ds = null;
            if (this.DataBindings["Text"] != null)
                ds = this.DataBindings["Text"].DataSource as DataSourceBinding;
            if (this.DataBindings["OpenDocumentBytes"] != null)
                ds = this.DataBindings["OpenDocumentBytes"].DataSource as DataSourceBinding;
            //if (this.DataBindings["BigImage"] != null)
            //    ds = this.DataBindings["BigImage"].DataSource as DataSourceBinding;
            if(ds == null)
            {
                if (OldBinding != null)
                    return OldBinding.DataSource as DataSourceBinding;
                else
                    return null;
            }
            return ds;
        }
        #region IOwningDataSourceBinding 成员
        private Binding _oldBinding;
        public Binding OldBinding
        {
            get
            {
                return _oldBinding;
            }
            set
            {
                _oldBinding = value;
            }
        }
        [Browsable(false)]
        public DataSourceBinding OwningDataSourceBinding
        {
            get { return GetOwningDataSourceBinding(); }
        }

        [Browsable(false)]
        DataSourceBinding IOwningDataSourceBinding.OwningDataSourceBinding
        {
            get { return OwningDataSourceBinding; }
        }

        [Browsable(false)]
        public DataItem BindingItem
        {
            get
            {
                return GetBindingItem();
            }
        }

        #endregion

        #region IReadOnly 成员

        private Color oldForeColor;
        //public new bool ReadOnly
        //{
        //    get
        //    {
        //        return this.ReadOnly;
        //    }
        //    set
        //    {
        //        this.ReadOnly = value;
                

        //    }
        //}

        #endregion
        /// <summary>
        /// 触发获取引用字段
        /// </summary>
        private bool FireRef = false;
        
      //  private Color oldBackColor;
        //protected override void OnGotFocus(EventArgs e)
        //{
        //    oldBackColor = this.BackColor;
        //    this.BackColor = Fcdbas.WinUI.Common.AppEnvironment.AppOption.FocusColor;
        //    base.OnGotFocus(e);
        //}
        private string _filePath;
        [Browsable(true)]
        [Category("Fcdbas")]
        [Description("指定绑定的富文本文件")]
        [Bindable(true)]
        public string FilePath
        {

            get
            {
               
                return _filePath;
            }
            set
            {
                _filePath = value;
                if (!System.IO.File.Exists(value))
                    return;
                byte[] bytes ;
                Fcdbas.Core.Util.FileHelper.ReadFileToBuff(value, out bytes);
                this.OpenDocumentBytes = bytes;
            }
        }
        protected override void OnLostFocus(EventArgs e)
        {
           // this.BackColor = oldBackColor;
            if (FireRef)
            {
                BaseForm parentForm = this.FindForm() as BaseForm;
                if (parentForm != null)
                    parentForm.FireOnTextChangedEvent(this);
                FireRef = false;
            }
            base.OnLostFocus(e);
        }
        
        protected override void OnEnter(EventArgs e)
        {
            BaseForm parentForm = this.FindForm() as BaseForm;
            if (parentForm != null)
                parentForm.FireOnEnterEvent(this);

            base.OnEnter(e);
        }
        public bool Validate()
        {
            DataSourceBinding ownerDataSourceBinding = GetOwningDataSourceBinding();
            if (DataColumn != null &&
                   DataColumn.Required &&
                   this.Text == null)
            {
                WinUI.Forms.BaseForm form = this.FindForm() as WinUI.Forms.BaseForm;
                if (form != null)
                    form.ShowMessage("字段[%%1]不能为空！", DataColumn.Caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            return true;
           // return ownerDataSourceBinding.Validate(this.DataColumn.ColumnName, this.Text);
        }
         
    }
}
